import 'dart:convert';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:orginone/components/EntityWidget/EntitySwitchWidget/EntitySwitchWidget.dart';
import 'package:orginone/components/XDialogs/LoadingDialog.dart';
import 'package:orginone/components/EmptyWidget/EmptyWidget.dart';
import 'package:orginone/dart/base/common/commands.dart';
import 'package:orginone/dart/base/model.dart';
import 'package:orginone/dart/base/schema.dart';
import 'package:orginone/dart/core/thing/standard/page.dart';
import 'package:orginone/main.dart';
import 'package:orginone/pages/portal/morepage/item_card.dart';
import 'package:orginone/pages/portal/morepage/service.dart';
import 'package:orginone/dart/core/thing/standard/form.dart' as form1;
import 'package:orginone/routers/index.dart';

import '../../../components/EntityWidget/EntitySwitchWidget/model.dart';
import '../../../components/PortalManagerWidget/portalrefresh_event.dart';

class SharePage extends StatefulWidget {
  const SharePage({Key? key}) : super(key: key);

  @override
  State<SharePage> createState() => _SharePageState();
}

class _SharePageState extends State<SharePage> {
  // List<IPageTemplate> iPages = [];
  // IPageTemplate? iPageTemplate;
  final EasyRefreshController refreshController = EasyRefreshController();
  // int loadIndex = 0;
  // int pageNum = 10;
  // List listThing = [];
  // int totalCount = 10;
  // String TAG = "sharepage";
  // // ignore: avoid_init_to_null
  form1.Form? formByPage;

  @override
  void initState() {
    super.initState();
    command.subscribeByFlag('switchApplication', ([args]) {
      if (mounted) {
        setState(() {});
      }
    });
    // loadPages();
  }

  // loadPages() async {
  //   iPages = await relationCtrl.loadPages();
  //   XPageTemplate? cachePages = await relationCtrl.user!.cacheObj
  //       .get<XPageTemplate>('pagetemplatemodule', XPageTemplate.fromJson);
  //   if (cachePages != null) {
  //     iPageTemplate =
  //         iPages.firstWhereOrNull((element) => element.id == cachePages.id);
  //   } else if (iPages.isNotEmpty) {
  //     iPageTemplate = iPages[0];
  //   }
  //   setState(() {});
  //   if (iPageTemplate != null) {
  //     onRefresh();
  //   }
  // }

  @override
  Widget build(BuildContext context) {
    PageTemplateData pageTemplateData = PageTemplateData("页面");
    return EntitySwitchWidget<IPageTemplate>(
        data: pageTemplateData,
        buildChildren: (IPageTemplate page) {
          return Future(() async {
            List list = await pageTemplateData.onRefresh(page);
            return list.isEmpty
                ? EmptyWidget()
                : EasyRefresh(
                    header: const MaterialHeader(),
                    footer: const MaterialFooter(),
                    controller: refreshController,
                    onRefresh: () async {
                      pageTemplateData.onRefresh(page);
                    },
                    onLoad: () async {
                      pageTemplateData.onLoadMore(page);
                    },
                    child: Container(
                      color: const Color(0xfff7f8fa),
                      child: buildPage(page, list),
                    ));
          });
        });
    // return EasyRefresh(
    //     header: const MaterialHeader(),
    //     footer: const MaterialFooter(),
    //     controller: refreshController,
    //     onRefresh: () async {
    //       onRefresh();
    //     },
    //     onLoad: () async {
    //       onLoad();
    //     },
    //     child: Container(
    //       // padding: const EdgeInsets.symmetric(horizontal: 12),
    //       color: const Color(0xfff7f8fa),
    //       child: SingleChildScrollView(
    //         child: Column(
    //           children: [
    //             buildSelectApp(),
    //             // buildIcon(),
    //             buildPage(),
    //           ],
    //         ),
    //       ),
    //     ));
  }

  // buildIcon() {
  //   return Container(
  //       color: Colors.white,
  //       margin: const EdgeInsets.only(bottom: 8),
  //       width: UIConfig.screenWidth,
  //       child: Row(mainAxisAlignment: MainAxisAlignment.spaceAround, children: [
  //         buildBtnWithTitleColumn('购物车',
  //             iconWidget: const Icon(
  //               Icons.shopping_cart,
  //               color: XColors.primary,
  //             ),
  //             onTap: () {}),
  //         // buildBtnWithTitleColumn('浏览记录',
  //         //     iconWidget: const Icon(
  //         //       Icons.shopping_cart,
  //         //       color: XColors.primary,
  //         //     ),
  //         //     onTap: () {}),
  //         buildBtnWithTitleColumn(
  //           '我的订单',
  //           iconWidget: const Icon(
  //             Icons.format_align_center,
  //             color: XColors.primary,
  //           ),
  //         ),
  //       ]));
  // }

  buildPage(IPageTemplate pageTemplate, List listThing) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 12),
      child: GridView.builder(
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          childAspectRatio: 0.65,
          mainAxisSpacing: 12,
          crossAxisSpacing: 12,
        ),
        padding: EdgeInsets.zero,
        itemCount: listThing.length,
        shrinkWrap: true,
        itemBuilder: (BuildContext context, int index) {
          return GestureDetector(
              onTap: () async {
                gotoFormDetail(pageTemplate, listThing, index);
              },
              child: ItemCard(item: listThing[index]));
        },
      ),
    );
  }

  // buildSelectApp() {
  //   return Container(
  //       padding: const EdgeInsets.all(16),
  //       margin: const EdgeInsets.only(bottom: 16),
  //       color: Colors.white,
  //       width: UIConfig.screenWidth,
  //       child: Row(
  //         children: [
  //           Expanded(
  //             child: SingleChildScrollView(
  //               scrollDirection: Axis.horizontal,
  //               child: Row(
  //                 children: [
  //                   Text(iPageTemplate?.name ?? "商城",
  //                       style: XFonts.size24Black0W700),
  //                   if (iPageTemplate != null &&
  //                       iPageTemplate!.groupTags.isNotEmpty)
  //                     Container(
  //                         margin: const EdgeInsets.only(left: 8),
  //                         padding: const EdgeInsets.fromLTRB(2, 6, 2, 6),
  //                         decoration: const BoxDecoration(
  //                             color: Color(0xfff2f3ff),
  //                             borderRadius:
  //                                 BorderRadius.all(Radius.circular(3))),
  //                         child: Text(iPageTemplate!.groupTags[0],
  //                             overflow: TextOverflow.ellipsis,
  //                             maxLines: 1,
  //                             style: TextStyle(
  //                                 fontSize: 14.sp, color: XColors.themeColor)))
  //                 ],
  //               ),
  //             ),
  //           ),
  //           const SizedBox(width: 4),
  //           GestureDetector(
  //             onTap: () {
  //               showSearchApplication(navigatorKey.currentState!.context, iPages,
  //                   title: "选择页面", hint: "搜索", onSelected: (selectData) async {
  //                 setState(() {
  //                   iPageTemplate = selectData[0];
  //                   formByPage = null;
  //                   onRefresh();
  //                 });
  //                 await relationCtrl.user!.cacheObj
  //                     .set('pagetemplatemodule', selectData[0].metadata);
  //               });
  //             },
  //             child: Row(
  //               children: [
  //                 Text('切换页面', style: XFonts.size22Black0),
  //                 const Icon(
  //                   Icons.arrow_forward_ios,
  //                   size: 18,
  //                 )
  //               ],
  //             ),
  //           )
  //         ],
  //       ));
  // }

  gotoFormDetail(IPageTemplate iPageTemplate, List listThing, int index) async {
    formByPage ??= await ShareServices().getFormBypagetemplete(iPageTemplate);
    if (formByPage != null) {
      LoadingDialog.showLoading(navigatorKey.currentState!.context);
      form1.Form form = formByPage!;
      List<FieldModel> fieds = await form.loadFields(reload: true);
      List<dynamic> data = ShareServices.assembleData(listThing[index], fieds);
      List<FieldModel> models =
          data.map((e) => FieldModel.fromJson(e)).toList();
      if (models.isNotEmpty) form.fields = models;
      LoadingDialog.dismiss(navigatorKey.currentState!.context);
      RoutePages.to(
          context: context, path: Routers.formDetailPreview, data: form);
    }
  }
}

class PageTemplateData extends EntitySwitchModel<IPageTemplate> {
  int loadIndex = 0;
  int pageNum = 10;
  List listThing = [];
  int totalCount = 10;
  form1.Form? formByPage;

  PageTemplateData(super.title);

  @override
  Future<IPageTemplate?> getInitData() async {
    IPageTemplate? iPageTemplate;
    XPageTemplate? cachePages = await relationCtrl.user!.cacheObj
        .get<XPageTemplate>('pagetemplatemodule', XPageTemplate.fromJson);
    if (cachePages != null) {
      iPageTemplate =
          datas.firstWhereOrNull((element) => element.id == cachePages.id);
    }
    iPageTemplate ??= datas.firstOrNull;
    return iPageTemplate;
  }

  @override
  Future<List<IPageTemplate>> getInitDatas() {
    return relationCtrl.loadPages();
  }

  @override
  void setCurrData(IPageTemplate? currData) async {
    if (null != currData) {
      XPageTemplate? xpageTemp = await relationCtrl.user!.cacheObj
          .get<XPageTemplate>('pagetemplatemodule', XPageTemplate.fromJson);
      var navigationItems =
          relationCtrl.user!.cacheObj.getValue("portalTemplate");
      if (null != navigationItems && navigationItems.isNotEmpty) {
        navigationItems.forEach((value) {
          if (value['name'] == xpageTemp!.name) {
            value['belongId'] = currData.belongId;
            value['name'] = currData.metadata.name;
            value['tags'] = ['共享模板', (currData.directory.metadata.name)];
            value['id'] =
                '${currData.metadata.belongId}_${currData.metadata.id}';
            value['metadata'] = currData.metadata;
            value['key'] =
                'home_Module${currData.metadata.belongId}_${currData.metadata.id}';
          }
        });
        relationCtrl.user!.cacheObj.set("portalTemplate", navigationItems);
        relationCtrl.user!.cacheObj
            .set('pagetemplatemodule', currData.metadata);
        portalRefreshEventBus.fire(PortalRefreshEvent(-1));
      }
    }
  }

  Future<List> onRefresh(IPageTemplate data,
      {bool shouldAllRead = false}) async {
    loadIndex = 0;
    await loadThingByPage(data, 0);
    return Future(() => listThing);
  }

  List onLoadMore(IPageTemplate data) {
    if (loadIndex * pageNum >= totalCount) return listThing;
    loadIndex++;
    loadThingByPage(data, loadIndex);
    return listThing;
  }

  loadThingByPage(IPageTemplate iPageTemplate, int index) async {
    List<String> relations = [
      iPageTemplate.directory.target.spaceId,
      iPageTemplate.directory.target.id
    ];

    formByPage ??= await ShareServices().getFormBypagetemplete(iPageTemplate);
    List filter = [];
    if (formByPage != null) {
      dynamic filterExp = jsonDecode(
          formByPage!.metadata.options?.dataRange?.filterExp ?? '[]');
      filter.addAll(filterExp);

      // dynamic classifyExp = jsonDecode(
      //     formByPage!.metadata.options?.dataRange?.classifyExp ?? '[]');
      // print(classifyExp);
      // filter.addAll(classifyExp);
    } else {
      return;
    }

    dynamic options = {
      'take': pageNum,
      'skip': (loadIndex) * pageNum,
      'requireTotalCount': true,
      'filter': filter,
      'userData': [],
      'options': [],
    };
    ResultType result = await ShareServices()
        .loadShopData(relations, options, iPageTemplate.belongId);
    if (result.success) {
      totalCount = result.data['totalCount'];
      List listRes = ShareServices()
          .getMallData(result.data['data'], iPageTemplate.metadata.rootElement);
      if (index == 0) {
        listThing.clear();
      }
      // setState(() {
      listThing.addAll(listRes);
      notifyListeners();
      // });
    }
  }
}
